package org.pentaho.obs.vfs;

import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileNameParser;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.VfsComponentContext;
import org.pentaho.huaweicloud.obs.OBSUtil;

public class OBSFileNameParser extends AbstractFileNameParser {
    private static final OBSFileNameParser INSTANCE = new OBSFileNameParser();

    public OBSFileNameParser() {
        super();
    }

    public static FileNameParser getInstance() {
        return INSTANCE;
    }

    public FileName parseUri( VfsComponentContext context, FileName base, String uri ) throws FileSystemException {
        StringBuilder buffer = new StringBuilder();

        String scheme = UriParser.extractScheme( uri, buffer );
        UriParser.canonicalizePath( buffer, 0, buffer.length(), this );

        // Normalize separators in the path
        UriParser.fixSeparators( buffer );

        // Normalise the path
        FileType fileType = UriParser.normalisePath( buffer );

        //URI includes credentials
        String keys = OBSUtil.getFullKeysFromURI( buffer.toString() );
        if ( keys != null ) {
            buffer.replace( buffer.indexOf( keys ), buffer.indexOf( keys ) + keys.length(), "" );
        }

        String path = buffer.toString();
        // Extract bucket name
        String bucketName = UriParser.extractFirstElement( buffer );

        if ( keys != null ) {
            bucketName = keys + bucketName;
            return new OBSFileName( scheme, bucketName, buffer.length() == 0 ? path : buffer.toString(), fileType, keys );
        }
        return new OBSFileName( scheme, bucketName, path, fileType );
    }
}
